const tree = require('./binTree.js')

// 二叉树层序遍历，输出多维数组
function levelOrder(root) {
    // 广度优先，将每个节点和他所在的层级组合成一个数组
    if (!root) return []
    const queue = [
        [root, 0]
    ]
    let res = []
    while (queue.length) {
        const [n, level] = queue.shift()
        if (res[level]) {
            res[level].push(n.val)
        } else {
            res[level] = [n.val]
        }
        if (n.left) {
            queue.push([n.left, level + 1])
        }
        if (n.right) {
            queue.push([n.right, level + 1])
        }
    }

    return res
}

const res = levelOrder(tree)
console.log(res)